﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using IPrinting;
using LogLib;
using PhotoPrinter;

namespace KPhotoPrinter
{
    public delegate void TakeLogInfo(string info);
    public delegate void UpdatePrintResult(string uploader, PrintResult result);
    public partial class ucInterfaceList : UserControl
    {
        public event TakeLogInfo TakeLog;
        protected void OnTakeLog(string info)
        {
            if (TakeLog != null)
            {
                TakeLog(info);
            }
        }

        private List<InterfaceConfig> ListInterfaceConfig = new List<InterfaceConfig>();

        public Dictionary<string, IPhotoPrint> AvailableInterfaces = new Dictionary<string, IPhotoPrint>();

        public Dictionary<string, IPhotoPrint> AllInterfaces = new Dictionary<string, IPhotoPrint>();

        private string _configfile = Application.StartupPath + "\\Config\\" + "Interfaces.xml";

        public ucInterfaceList()
        {
            InitializeComponent();
        }

        public void OnConfigRefreshed()
        {       
            ReleaseInterfaces();
            LoadInterface();
        }

        private void ReleaseInterfaces()
        {
            foreach (IPhotoPrint printApp in AvailableInterfaces.Values)
            {
                printApp.Exit();
            }
            AllInterfaces.Clear();
            AvailableInterfaces.Clear();
        }

        public void LoadInterface()
        {
            //配置文件路径
            InterfaceConfigReader<InterfaceConfig> reader = new InterfaceConfigReader<InterfaceConfig>(_configfile);
            //读配置
            if (!reader.Load())
            {
                MessageBox.Show("打印接口配置信息加载失败!\n" + reader.ErrorMessage);
            }
            ListInterfaceConfig = reader.ListInterfaces;
            CreatInterfaces();
        }

        private void CreatInterfaces()
        {
            dataGridView1.Rows.Clear();
            //实例化
            for (int i = 0; i < ListInterfaceConfig.Count; i++)
            {
                string msg;
                CreatUploader(ListInterfaceConfig[i], out msg);
                AddRow(i + 1, msg, ListInterfaceConfig[i]);
            }
            string info = string.Format("共加载{0}个接口", ListInterfaceConfig.Count);
            OnTakeLog(info);
        }

        private void CreatUploader(InterfaceConfig config, out string msg)
        {
            msg = "";
            string dllPath = string.Format("{0}\\{1}\\{2}.dll",
                   Application.StartupPath,
                   config.Directory,
                   config.DllName);
            if (!File.Exists(dllPath))
            {
                OnTakeLog(dllPath + "不存在.");
                msg = "dll不存在";
                MessageBox.Show("指定的文件路径不存在:" + dllPath);
                return;
            }
            Assembly assembly = Assembly.LoadFile(dllPath);
            IPhotoPrint uploader = (IPhotoPrint)assembly.CreateInstance(config.TypeName);
            if (uploader == null)
            {
                msg = "对象创建失败";
                MessageBox.Show("接口创建失败:" + config.InterfaceName);
                return;
            }
            uploader.ID = config.ID;
            uploader.TimeoutMillisecond = config.Timeout;
            AllInterfaces.Add(config.InterfaceName, uploader);
            if (config.Enable)
            {
                AvailableInterfaces.Add(config.InterfaceName, uploader);
                msg = "未初始化";
            }
            else
            {
                OnTakeLog("接口被禁用: " + config.InterfaceName);
                msg = "未启用";
            }
        }

        private void AddRow(int index, string status, InterfaceConfig config)
        {
            DataGridViewRow row = new DataGridViewRow();
            row.Height = 36;

            DataGridViewTextBoxCell idcell = new DataGridViewTextBoxCell();
            idcell.Value = index.ToString();
            row.Cells.Add(idcell);

            DataGridViewTextBoxCell classnamecell = new DataGridViewTextBoxCell();
            classnamecell.Value = config.InterfaceName;
            row.Cells.Add(classnamecell);

            DataGridViewTextBoxCell titlecell = new DataGridViewTextBoxCell();
            titlecell.Value = config.ChineseDescrtiption;
            row.Cells.Add(titlecell);

            DataGridViewCheckBoxCell enabledcell = new DataGridViewCheckBoxCell();
            enabledcell.Value = config.Enable;
            row.Cells.Add(enabledcell);

            DataGridViewTextBoxCell statuscell = new DataGridViewTextBoxCell();
            statuscell.Value = status;
            row.Cells.Add(statuscell);

            DataGridViewButtonCell initcell = new DataGridViewButtonCell();
            initcell.Value = "登录连接";
            row.Cells.Add(initcell);

            DataGridViewButtonCell settingcell = new DataGridViewButtonCell();
            settingcell.Value = "设置";        
            row.Cells.Add(settingcell);

            dataGridView1.Rows.Add(row);
        }

        public void UpdateActionResult(string uploader, PrintResult result)
        {
            string showInfo = "";
            switch (result)
            {
                case PrintResult.InitOK:
                    showInfo = "初始化成功";
                    break;
                case PrintResult.InitFailed:
                    showInfo = "初始化失败";
                    break;
                case PrintResult.ExitOK:
                    showInfo = "Exit成功";
                    break;
                case PrintResult.ExitFailed:
                    showInfo = "Exit失败";
                    break;
                case PrintResult.PrintOK:
                    showInfo = "打印成功";
                    break;
                case PrintResult.PrintFailed:
                    showInfo = "打印失败";
                    break;
                case PrintResult.CropPrintOK:
                    showInfo = "裁切打印成功";
                    break;
                case PrintResult.CropPrintFailed:
                    showInfo = "裁切打印失败";
                    break;
                case PrintResult.ClearOK:
                    showInfo = "清理打印队列成功";
                    break;
                case PrintResult.ClearFailed:
                    showInfo = "清理打印队列失败";
                    break;
                case PrintResult.Timeout:
                    showInfo = "操作超时";
                    break;
                case PrintResult.CatchException:
                    showInfo = "捕获到异常";
                    break;
                default:
                    break;
            }
          
            Action handler = () =>
            {
                int index = ListInterfaceConfig.FindIndex(r => r.InterfaceName.Equals(uploader));
                if (index == -1)
                {
                    Log.WriteAsync("没有找到接口对象:" + uploader);
                    return;
                }
                if (dataGridView1.Rows.Count <= index)
                {
                    Log.WriteAsync("无效的应用程序对象索引:" + index);
                    return;
                }
                DataGridViewRow row = dataGridView1.Rows[index];
                row.Cells[4].Value = showInfo;                        
            };
            this.Invoke(handler);
        }

        private void ucInterfaceList_Load(object sender, EventArgs e)
        {
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 5
                || e.ColumnIndex == 6
                || e.ColumnIndex == 7)
            {
                DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                string interfaceName = (string)row.Cells[1].Value;
                
                IPhotoPrint handle = AllInterfaces[interfaceName];
                int function = e.ColumnIndex;
                if (function == 5) //初始化
                {
                    string outParam = "";
                    if (handle.Init("", out outParam))
                    {
                        UpdateActionResult(handle.Name, PrintResult.InitOK);
                    }
                    else
                    {
                        MessageBox.Show(handle.ErrorMessage);
                    }
                }               
                if (function == 6)//设置
                {
                    handle.ShowConfigDialog("");
                }
            }
        }

    }
}
